<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax之get请求初步封装</title>
</head>
<body>
    <script>
        ajax("GET","./04_ajax_first.php",function(data){
            console.log(data);
        },{
            username:"kuiya"
        });


        // ajax_get请求初步封装
        function ajax(method,url,callback,dataObj){
            var xhr = new XMLHttpRequest();
            xhr.open(method,formateUrl(url,dataObj));
            xhr.send();
            xhr.onreadystatechange = () =>{
                if(xhr.readyState ===4 && /^2\d{2}$/.test(xhr.status)){
                    callback(xhr.responseText);
                }
            }
        }

        // get请求的url路径拼接
        function formateUrl(url,dataObj){
            var start = true;
            for(var key in dataObj){
                url += (start?"?":"&") + key + '=' + dataObj[key];
            }
            return url;
        }
    </script>
</body>
</html>